import store from "../store/store";
import { setShowOverlay } from '../store/action'
import { createNewRoom, joinRoom, signalPeerData } from "./wss";
import Peer from 'simple-peer'
const defaultContraints = {
    audio:true,
    video:{width:"480",height:"360"},
};
let localStream;
export const getLocalPreviewAndInitRoomConnection = async (
    isRoomHost,identity,roomId = null) => {
        //采集本地音视频流
        navigator.mediaDevices.getUserMedia(defaultContraints).then((stream)=>{
            localStream = stream;
            console.log('成功加载本地流')
            store.dispatch(setShowOverlay(false));
            //预览本地视频
            showLocalVideoPreview(stream)

            //初始化房间链接
            isRoomHost?createNewRoom(identity):joinRoom(identity,roomId);

        }).catch((error) =>{
            console.log(error);
        })

}


/**
 * NAT 穿越问题 产生的STUN服务器
 * https://codeleading.com/article/1253592404/
 * @returns STUN服务器配置
 */
//配置STUN服务器
//配置STUN服务器
const getConfiguration = () => {
    return {
      iceServers: [
        {
          urls: 'stun:stun1.l.google.com:19302',
        },
      ],
    };
  };
  
let peers = {};
let streams = [];
//准备webRTC对等连接
export const prepareNewPeerConnection = (connUserSocketId,isInitiator) =>{
    const configuration = getConfiguration();
    peers[connUserSocketId] = new Peer({
        initiator:isInitiator,
        config:configuration,
        stream:localStream,
        trickle:true
    })
    console.log(peers[connUserSocketId]);
    //信令数据交换
    //信令数据传递
  peers[connUserSocketId].on('signal', (data) => {
    //==>peer1.on('signal', data)
    //data - webrtc offer, answer, or ice candidate
    console.log(data)
    const signalData = {
      signal: data,
      connUserSocketId: connUserSocketId,
    };
    signalPeerData(signalData);
  });

    //获取媒体流stream
    peers[connUserSocketId].on('stream',(stream) =>{
        console.log('成功获取远端stream')
        //显示接收的stream媒体流
        addStream(stream,connUserSocketId);
        streams = [...streams,stream]
    })
}
//将信令数据添加接收webrtc对等连接准备的一方的对等连接
export const handleSignalingData = (data) =>{
    peers[data.connUserSocketId].signal(data.signal);
}
//本地预览
const showLocalVideoPreview = (stream) => {
    const videosContainer = document.getElementById('videos_portal');
    videosContainer.classList.add('videos_portal_styles');
    const videoContainer = document.createElement('div');
    videoContainer.classList.add('video_track_container');

    const videoElement = document.createElement('video');
    videoElement.autoplay = true;
    videoElement.muted = true;
    videoElement.srcObject = stream;
    videoElement.onloadedmetadata = () =>{
        videoElement.play();
    }
    videoContainer.appendChild(videoElement);
    videosContainer.appendChild(videoContainer);
}
// 对端视频流
const addStream = (stream,connUserSocketId) =>{
    const videosContainer = document.getElementById('videos_portal');
    const videoContainer = document.createElement('div');
    videoContainer.id = connUserSocketId;
    videoContainer.classList.add('video_track_container');

    const videoElement = document.createElement('video');
    videoElement.autoplay = true;
    videoElement.muted = true;
    videoElement.srcObject = stream;
    videoElement.id = `${connUserSocketId}-video`;
    videoElement.onloadedmetadata = () =>{
        videoElement.play();
    }
    // 放大缩小
    videoElement.addEventListener('click',()=>{
      if(videoElement.classList.contains('full_screen')){
        videoElement.classList.remove('full_screen')
      }else{
        videoElement.classList.add('full_screen');
      }
    })
    videoContainer.appendChild(videoElement);
    //very import 容器的style位置为static 才能点击他方显示放大缩小功能
    videoContainer.style.position = 'static';
    videosContainer.appendChild(videoContainer);
}

export const removePeerConnection = (data) =>{
  const {socketId} = data;

  const videoContainer = document.getElementById(socketId);
  const videoElement = document.getElementById(`${socketId}-video`);
  if(videoContainer && videoElement){
    const tracks = videoElement.srcObject.getTracks();
    tracks.forEach((track) => track.stop());
    videoElement.srcObject = null;
    videoContainer.removeChild(videoElement);
    videoContainer.parentNode.removeChild(videoContainer);

    if(peers[socketId]){
      peers[socketId].destroy();
    }
    delete peers[socketId];
  }
}